package org.dromara.handle;

import lombok.extern.slf4j.Slf4j;
import org.dromara.entity.Result;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

@Slf4j
@RestControllerAdvice
public class GlobalException {

    /**
     * 校验异常处理
     * 产生原因：使用@RequestBody注解，参数校验未通过，抛出MethodArgumentNotValidException异常
     * @param  e 校验异常
     * @return 处理结果
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result MethodArgumentNotValidException(MethodArgumentNotValidException e) {
        StringBuilder message = new StringBuilder();
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        for (FieldError fieldError : fieldErrors) {
            message.append(fieldError.getField()).append(fieldError.getDefaultMessage()).append(",");
        }
        message = new StringBuilder(message.substring(0, message.length()-1));
        return Result.fail(message.toString());
    }




}
